import _ from 'loadsh'
import React from 'react'
import moment from 'moment'
import { Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { pk } from './config'
import { decrypt } from '@js/jsencrypt'
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
const { confirm } = Modal

// await 错误处理方法
export async function awaitWrap (promise) {
  return await promise
    .then((data) => [null, data])
    .catch(err => [err, null])
}

// 验证文件是否为空
export function validateFileRequire (notice = '') {
  return {
    validator (_, value) {
      if (!value) {
        return Promise.resolve()
      } else if (value.fileList.length === 0) {
        return Promise.reject(new Error(notice))
      }
      return Promise.resolve()
    }
  }
}

// 获取文件上传的配置
export function getUploadProps (formRef, accept) {
  return {
    onRemove: file => {
      this.setState(state => {
        const index = state.fileList.indexOf(file)
        const newFileList = state.fileList.slice()
        newFileList.splice(index, 1)
        return {
          fileList: newFileList
        }
      })
    },
    beforeUpload: file => {
      this.setState(state => {
        const fileList = [...state.fileList, file]
        return {
          fileList
        }
      })
      return false
    },
    fileList: this.state.fileList,
    accept
  }
}

// 获取文件上传的配置
export function getUploadPropsFn (formRef, accept, fileList, setFileList) {
  return {
    onRemove: file => {
      const index = fileList.indexOf(file)
      const newFileList = fileList.slice()
      newFileList.splice(index, 1)
      setFileList(newFileList)
    },
    beforeUpload: file => {
      setFileList([...fileList, file])
      return false
    },
    fileList,
    accept
  }
}

// 仲裁请求文本分项
export function splitItem (text) {
  text = text.trim()
  const cnNum = '一二三四五六七八九十' // 中文数字
  const pre = '\\u4e00-\\u9fa5a-zA-Z#\\-：:\'"‘’“”' // 序号前不能接的字符
  const numPre = `${pre}\\d\\.` // 阿拉伯数字序号前不能接的字符
  const split = '、,\\.，．' // 序号后的分隔符
  let nReplace = '$2$3$4$5$6$7\n'
  // 综合判断中文和阿拉伯数字序号
  let r = `(^[${cnNum}\\d][${split}]|(?=[^${numPre}]\\d{3}[${split}])(.)....|(?=[^${numPre}]\\d{2}[${split}])(.)...|(?=[^${numPre}]\\d[${split}])(.)..|(?=[^${pre}][${cnNum}]{3}[${split}])(.)....|(?=[^${pre}][${cnNum}]{2}[${split}])(.)...|(?=[^${pre}][${cnNum}][${split}])(.)..)(?![${cnNum}\\d]+)`
  if (cnNum.indexOf(text[0]) !== -1) { // 起始为中文序号时，只判断中文序号
    r = `(^[${cnNum}][${split}]|(?=[^${pre}][${cnNum}]{3}[${split}])(.)....|(?=[^${pre}][${cnNum}]{2}[${split}])(.)...|(?=[^${pre}][${cnNum}][${split}])(.)..)`
    nReplace = '$2$3$4\n'
  } else if (/\d/.test(text[0])) { // 起始为阿拉伯数字序号时，只判断阿拉伯数字序号
    r = `(^\\d[${split}]|(?=[^${numPre}]\\d{3}[${split}])(.)....|(?=[^${numPre}]\\d{2}[${split}])(.)...|(?=[^${numPre}]\\d[${split}])(.)..)(?!\\d+)`
    nReplace = '$2$3$4\n'
  }
  const reg = new RegExp(r, 'gim')
  // const nRef = new RegExp(`(\\r\\n?|\\n)(?![${cnNum}]+[${split}])`, 'g')
  let result = text.replace(reg, nReplace).split('\n').map(li => li.trim()).filter(li => li)
  result = _.uniqWith(result, _.isEqual)
  return result
}

// 格式化金钱
export function formatMoney (v, empty = '0') {
  v = strToNum(v)
  if (v) {
    return v.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  }
  return empty
}

// 格式化日期
export function formatDate (t, format = 'YYYY-MM-DD') {
  t = strToNum(t)
  if (t > 0) {
    return moment(t * 1000).format(format)
  }
  return t
}

// 限制字符串长度
export function limitStr (str, limit = 50) {
  if (typeof str === 'string' && str.length > limit) {
    return str.slice(0, limit) + '...'
  }
  return str
}

// 二次确认
export function confirmAction (content, callback) {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content,
    onOk () {
      callback()
    }
  })
}

// 提示信息
export function infoAction (content) {
  Modal.info({
    icon: <ExclamationCircleOutlined />,
    content,
    okText: '确定'
  })
}

// 公钥加密
export function compress (v) {
  // const key = new NodeRSA(pk, undefined, { encryptionScheme: 'pkcs1' })
  // const str = key.encrypt(v, 'base64')
  try {
    const encryptTool = new JSEncrypt()
    encryptTool.setPublicKey(pk)
    const str = encryptTool.encrypt(v)
    if (typeof str === 'string') {
      return str
    }
  } catch (e) {
    console.error(e)
  }
  return ''
}

// 公钥解密
export function decompress (v) {
  try {
    const str = decrypt(v, pk)
    if (typeof str === 'string') {
      return str
    }
  } catch (e) {
    console.error(e)
  }
  return ''
}

// 格式化案件件证件号
export function formatCaseDataLicense (d) {
  const keys = ['applicant_agents', 'applicants', 'respondents', 'respondents_agents']
  keys.forEach(key => {
    const arr = d[key]
    if (arr instanceof Array && arr.length > 0) {
      arr.forEach(li => {
        if (typeof li.license === 'string' && li.license.length > 0) {
          li.license = decompress(li.license)
        }
      })
    }
  })
  return d
}

export function compressLicenseAndMobile (o) {
  if (o && typeof o.license === 'string' && o.license.length > 0) {
    o.license = compress(o.license)
  }
  if (o && typeof o.mobile === 'string' && o.mobile.length > 0) {
    o.mobile = compress(o.mobile)
  }
}

export function decompressLicenseAndMobile (o) {
  if (o && typeof o.license === 'string' && o.license.length > 0) {
    o.license = decompress(o.license)
  }
  if (o && typeof o.mobile === 'string' && o.mobile.length > 0) {
    o.mobile = decompress(o.mobile)
  }
}

export function compressListLicenseAndMobileAndBank (l) {
  if (l instanceof Array && l.length > 0) {
    l.forEach(li => {
      compressLicenseAndMobile(li)
      if (typeof li.bank_accountno === 'string' && li.bank_accountno.length > 0) {
        li.bank_accountno = compress(li.bank_accountno)
      }
    })
  }
}

export function decomporessListLicenseAndMobileAndBank (l) {
  if (l instanceof Array && l.length > 0) {
    l.forEach(li => {
      decompressLicenseAndMobile(li)
      if (typeof li.bank_accountno === 'string' && li.bank_accountno.length > 0) {
        li.bank_accountno = decompress(li.bank_accountno)
      }
    })
  }
}

// 将字符串数字转为数字类型
export function strToNum (v) {
  if (typeof v === 'number') {
    return v
  } else if (typeof v === 'string' && !isNaN(Number(v))) {
    return Number(v)
  }
  return 0
}
